import time
import traceback
from flask import Blueprint, jsonify, request
from sqlalchemy import or_

from application import db
from models import Menu

menu_bp = Blueprint('menu_pb', __name__)


# 渲染后台管理系统的菜单接口
@menu_bp.route('/')
def get_menus():
    data = {
        'menus': [],
        'meta': {
            'msg': 'success',
            'status': 200
        }
    }
    menus = Menu.query.filter_by(parent_id=0).all()
    try:
        menus = [
            {
                'id': m.id,
                'name': m.name,
                'route': m.route,
                'sub_menus': [{
                    'id': sm.id,
                    'name': sm.name,
                    'route': sm.route,
                } for sm in Menu.query.filter_by(parent_id=m.id).all()]
            }
            for m in menus
        ]
    except Exception as e:
        traceback.print_exc()
        data['msg'] = 'fail'
        data['status'] = 400
        return jsonify(data)
    data['menus'] = menus
    return jsonify(data)


# 获取所有表格数据
@menu_bp.route('/list')
def menus_list():
    key = request.args.get('key')
    current_page = int(request.args.get('currentPage'))
    page_size = int(request.args.get('pageSize'))
    data = {
        'menus': [],
        'total': 0,
        'meta': {
            'msg': 'success',
            'status': 200
        }
    }

    # 关键字搜索
    if key:
        menus = Menu.query.filter(or_(
            Menu.name.contains(key),
            Menu.desc.contains(key)
        )).paginate(current_page, page_size).items
    else:
        menus = Menu.query.paginate(current_page, page_size).items
    try:
        menus = [
            {
                'id': m.id,
                'name': m.name,
                'route': m.route,
                'desc': m.desc,
                'menu_level': m.menu_level,
                'parent_id': m.parent_id,
                'create_time': m.create_time.strftime('%Y-%m-%d %X'),
                'update_time': m.update_time.strftime('%Y-%m-%d %X')
            }
            for m in menus
        ]
    except Exception as e:
        traceback.print_exc()
        data['meta']['msg'] = 'fail'
        data['meta']['status'] = 400
        return jsonify(data)
    data['menus'] = menus
    data['total'] = len(menus)
    return jsonify(data)


# 添加菜单项
@menu_bp.route('/add', methods=['POST'])
def add_menu():
    form = request.json
    data = {
        'meta': {
            'msg': 'success',
            'status': 200
        }
    }
    menu = Menu(
        name=form['name'],
        route=form['route'],
        parent_id=form.get('parent_id', 0),
        desc=form['desc'],
        menu_level=form['level']
    )
    try:
        db.session.add(menu)
        db.session.commit()
    except Exception as e:
        traceback.print_exc()
        data['msg'] = 'fail'
        data['status'] = 400
        return jsonify(data)
    return jsonify(data)


@menu_bp.route('/delete/<int:mid>', methods=['DELETE'])
def del_menu(mid):
    data = {
        'meta': {
            'msg': 'success',
            'status': 200
        }
    }
    try:
        menu = Menu.query.filter_by(id=mid).first()
        print(menu)
        db.session.delete(menu)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        traceback.print_exc()
        data['meta']['msg'] = 'fail'
        data['meta']['status'] = 400
        return jsonify(data)
    return jsonify(data)
